#include "myBTIt.h"
#include <malloc.h>

void LExtBTIList(MyList *bTIList, LNTYPE next) {
    while(next) {
        myListInsertDataAtLast(bTIList, next);
        next = next->left;
    }
}

void RExtBTIList(MyList *bTIList, LNTYPE next) {
    while(next) {
        myListInsertDataAtLast(bTIList, next);
        next = next->right;
    }
}

LNTYPE l2rExtL(LNTYPE pre) {
    return pre->right;
}

LNTYPE r2lExtL(LNTYPE pre) {
    return pre->left;
}


int bTIthasNext(BTI *bTIP) {
    return bTIP->bTIList->count > 0;
}

LNTYPE bTItNext(BTI *bTIP) {
    LNTYPE btp = myListRemoveDataAtLast(bTIP->bTIList);
    (*bTIP->extBTIList)(bTIP->bTIList, (*bTIP->extLinker)(btp));
    return btp;
}


BTI *createBTIt(LNTYPE root, void (*extBTIList)(MyList *bTIList, LNTYPE next), LNTYPE (*extLinker)(LNTYPE pre)) {
    MyList *bTIList = createMyList();
    (*extBTIList)(bTIList, root);
    BTI *bTIP = malloc(sizeof(BTI));
    bTIP->bTIList = bTIList;
    bTIP->extBTIList = extBTIList;
    bTIP->extLinker = extLinker;
    return bTIP;
}

void myBTItFree(BTI *bTIt) {
    freeMyList(bTIt->bTIList);
    free(bTIt);
}

//*******************TestCode***********
#include <stdio.h>
#include "/root/GitLib/LeetCode/levelOrder.h"
int main(void)
{
    int a[] = {10,4,18,-1,5,17,19};
    TNode *root = NULL;
    levelOrder_init(&root, a, 7, 0);
    BTI *bTITestl = createBTIt(root, LExtBTIList, l2rExtL);
    BTI *bTITestr = createBTIt(root, RExtBTIList, r2lExtL);
    while(bTIthasNext(bTITestl)) {
        printf("%d,", bTItNext(bTITestl)->val);
    }
    puts("\n\n");
    while(bTIthasNext(bTITestr)) {
        printf("%d,", bTItNext(bTITestr)->val);
    }
    puts("\n\n");
    myBTItFree(bTITestl);
    myBTItFree(bTITestr);
    return 0;
}

/**************************************/

